// Initialize your app
var myApp = new Framework7({
   // If it is webapp, we can enable hash navigation:
    pushState: true
    
});

// Export selectors engine
var $$ = Dom7;

// Add view
var mainView = myApp.addView('.view-main', {
    // Because we use fixed-through navbar we can enable dynamic navbar
    dynamicNavbar: true,
	domCache: false,
});

// Callbacks to run specific code for specific pages, for example for About page:
myApp.onPageInit('about', function (page) {
    // run createContentPage func after link was clicked
    $$('.create-page').on('click', function () {
        createContentPage();
    });
});

var ifLogin = false; 
var checkLogin = function(){
	$$.ajax({
		type: "get",
		dataType: "json",
		url: "/check",
		success: function(response){
			if(response.result == 1)
			{
				ifLogin = true;
			} else if( response.result == 0) {
				ifLogin = false;
			}
		}
	}); 
}
checkLogin();

$$(document).on('pageInit', '.page[data-page^="ask-item"]', function (e) {
    $$('.comment-popup').on('click', function(){
        var url = $$(this).attr('href').substring(1);
		if(ifLogin)
		{
		   myApp.pickerModal(getCommentPopup(url));
		   $$('#content').focus();
		} else {
		   actionLogin('');
		}
    });

    $$('.item-like').on('click', function(){
		like($$(this));
    });

	$$('.item-collect').on('click', function(){
		collect($$(this));
    });

	/*$$('.reply-post').click(function(){
		if(ifLogin == true)
		{
			var formData = myApp.formToJSON('#reply-form');
			$$.ajax({
				type: "post",
				url: "/ask/comment/"+formData.post_id,
				data: "content=" + formData.content,
				success: function(response){
					$$('.comments').append(response);
					$$('#content').val('');
				}
			});
		} else {
		   actionLogin();
		}
	
	})*/
})

$$(document).on('pageInit', '.page[data-page^="search-user"]', function (e) {
   $$('.item-like').on('click', function(){
		like($$(this));
    }); 
	$$('.show-avatar').on('click', function(){
		var myPhotoBrowser = myApp.photoBrowser({
			zoom: 400,
			photos: [$$(this).attr('src')],
			navbar : false,
			toolbar : false,
			theme : 'dark'
		});   
		myPhotoBrowser.open(); 
    });
	$$('.check-tel').on('click', function(){
		if(ifLogin)
		{
		   var tel = $$(this).attr('data-tel');
		   myApp.modal({
			title: '联系方式',
			text: tel.length > 1 ? tel : '暂空',
			buttons:[
				{
					text:'取消',
					close: true,
				},
				{
					text:'拨打',
					onClick: function(){
						if(tel.length>6)
						{
							url = "tel:"+tel;
							location.href=url;
						}
				}
				}
			]
		});
		} else {
		   actionLogin('');
		}
	
	});
})

$$(document).on('pageInit', '.page[data-page^="search-user"]', function (e) {
    $$('.item-collect').on('click', function(){
		collect($$(this));
    });
})

myApp.onPageInit('*', function (page) {
    $$('.station-letter-popup').on('click', function(){
        var url = $$(this).attr('href').substring(1);
        if(ifLogin)
        {
            myApp.pickerModal(getStationLetterPopup(url));
            $$('#content').focus();
        } else {
            actionLogin('');
        }
    });
});

var like = function(obj){
		var me = $$(obj);
        var item = $$(obj).attr('id').split('-');
		var like_type  = item[0];
		var item_id = item[1];
        $$.ajax({
				type: "get",
				dataType: "json",
				url: "/like/like",
				data: "like_type=" + like_type + "&item_id=" + item_id,
				success: function(response){
					var like_cnt = parseInt($$(me).find('.like-badge').html());
					if(response && response.type == 'success')
					{
						$$(me).find('.like-badge').html(++like_cnt);	
					} else if( response.type == 'error') {
						if(response.msg && response.msg == 'unsignin')
						{
							var url = $$(this).attr('href').substring(1);
							actionLogin(url);					
						} else {
							 //已赞过
						}
					}
				}
		});
}

var collect = function(obj){
		var me = $$(obj);
        var item = $$(obj).attr('id').split('-');
		var like_type  = item[0];
		var item_id = item[1];
        $$.ajax({
				type: "get",
				dataType: "json",
				url: "/collect/collect",
				data: "collect_type=" + like_type + "&item_id=" + item_id,
				success: function(response){
					var collect_cnt = parseInt($$(me).find('.collect-badge').html());
					if(response && response.type == 'success')
					{
						$$(me).find('.collect-status').html('已收藏');
						$$(me).find('.collect-badge').html(++collect_cnt);	
					} else if( response.type == 'error') {
						if(response.msg && response.msg == 'unsignin')
						{
							actionLogin('');
				
						} else {
							 //已收藏
						}
					}
				}
		});
}

var actionLogin = function(url){
	// 弹出注册登录窗口
	var buttons = [
		{
			text: '请先登录',
			label: true
		},
		{
			text: '马上登录',
			onClick: function () {
				location.href= "/login?backurl="+url;
			}
		}
	];
	myApp.actions(buttons);
}

var getStationLetterPopup = function(actionUrl){
    var popupHTML = '<div class="popup">'+
        '<div class="content-block">'+
        '<p>留言</p>'+
        '<form action="'+actionUrl+'" method="post">' +
        '<input type="hidden" name="current_page" value="'+window.location.href+'" />' +
        '<div class="item-content">' +
        '<div class="item-inner">' +
        '<div class="item-input input-box">' +
        '<textarea name="content" class="input-control" placeholder="留言"></textarea>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '<div class="content-block row">' +
        '<div class="col-50"><input type="submit" class="button button-blue button-fill" value="提交" /></div>' +
        '<div class="col-50"><input type="button" class="close-popup button button-fill color-blue" value="取消" /></div>' +
        '</div>' +
        '</form>'+
        '</div>'+
        '</div>';

    return popupHTML;
};

var getCommentPopup = function(actionUrl){
    var popupHTML = '<div class="popup">'+
        '<div class="content-block">'+
        '<p>发表回复</p>'+
        '<form action="'+actionUrl+'" method="post">' +
        '<input type="hidden" name="current_page" value="'+window.location.href+'" />' +
        '<div class="item-content">' +
        '<div class="item-inner">' +
        '<div class="item-input input-box">' +
        '<textarea name="content" class="input-control" placeholder="回复问题"></textarea>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '<div class="content-block row">' +
        '<div class="col-50"><input type="submit" class="button button-blue button-fill" value="提交" /></div>' +
        '<div class="col-50"><input type="button" class="close-popup button button-fill color-blue" value="取消" /></div>' +
        '</div>' +
        '</form>'+
        '</div>'+
        '</div>';

    return popupHTML;
};

// Generate dynamic page
var dynamicPageIndex = 0;
function createContentPage() {
	mainView.router.loadContent(
        '<!-- Top Navbar-->' +
        '<div class="navbar">' +
        '  <div class="navbar-inner">' +
        '    <div class="left"><a href="#" class="back link"><i class="icon icon-back"></i><span>Back</span></a></div>' +
        '    <div class="center sliding">Dynamic Page ' + (++dynamicPageIndex) + '</div>' +
        '  </div>' +
        '</div>' +
        '<div class="pages">' +
        '  <!-- Page, data-page contains page name-->' +
        '  <div data-page="dynamic-pages" class="page">' +
        '    <!-- Scrollable page content-->' +
        '    <div class="page-content">' +
        '      <div class="content-block">' +
        '        <div class="content-block-inner">' +
        '          <p>Here is a dynamic page created on ' + new Date() + ' !</p>' +
        '          <p>Go <a href="#" class="back">back</a> or go to <a href="services.html">Services</a>.</p>' +
        '        </div>' +
        '      </div>' +
        '    </div>' +
        '  </div>' +
        '</div>'
    );
	return;
}

// edit field
$$(document).on('pageInit', '.page[data-page^="field"]', function (e) {
	if ( cur_field_label!= '' ){
		$$('.field-name').html(cur_field_label);
	}  
});
var cur_field_label = '';
$$(document).on('click','.field-link',function(e){
	cur_field_label = $$(this).find('.label').text();
});

$$(document).on('pageInit', '.page[data-page="field-setting-workscope"]', function (e) {
   $$('.save').on('click', function(){
		if($$('#workscope_frm .ck:checked').length < 4)
		{
			$$('#workscope_frm').submit();
		} else {
			myApp.alert('最多选择三个专业。', '温馨提示');
		}
	}); 
	$$('#workscope_frm .ck').on('click', function(){
		if($$('#workscope_frm .ck:checked').length>3){
			$$(this).prop('checked', false);
			myApp.alert('最多选择三个专业。', '温馨提示');
		}
	});
})

$$.fn.valignImg = function(wWidth, wHeight){
	$$(this).each(function(){
		if($$(this).hasClass('valign-img'))return;
		var pWidth = $$(this).width();
		var pHeight = $$(this).height();

		if(pWidth > wWidth && pHeight > wHeight )
		{
			var scale = pWidth < pHeight ? wWidth/pWidth : wHeight/pHeight;
			nWidth = pWidth*scale;
			nHeight = pHeight*scale;

			_top = (wHeight - nHeight)/2;
			_left = (wWidth - nWidth)/2;

		} else if(pWidth < wWidth || pHeight < wHeight) {
			nWidth = pWidth;
			nHeight = pHeight;
			_top = (wHeight - nHeight)/2;
			_left = (wWidth - pWidth)/2;
		}

		$$(this).css({
			'width': Math.round(nWidth)+'px',
			'height': Math.round(nHeight)+'px',
			'top': Math.round(_top)+'px',
			'left': Math.round(_left)+'px',
		});
		$$(this).addClass('valign-img');


	});

	return this;
};

$$(document).on('click', '.indev', function(){
	myApp.alert('开发中，敬请期待！', '我的律团网');
});
$$(document).on('click', '.btn-apply', function(){
	var data = myApp.formToJSON('#apply-frm');
	var company_name = typeof data.company_name != 'undefined' ? data.company_name : '';
	var content = typeof data.content != 'undefined' ? data.content : '';
	var category_id = typeof data.category_id != 'undefined' ? data.category_id: '0';
	var is_urgent = typeof data.quick != 'is_urgent' ? data.is_urgent : '';
	$$.ajax({
		type: "post",
		dataType: "json",
		data: {'promotion_id':data.promotion_id,'contact_name':data.contact_name,'contact':data.contact, 'email':data.email,'company_name':company_name,'content':content,'category_id':category_id,'is_urgent':is_urgent},
		url: "/apply",
		success: function(response){
			if(response.result == 1)
			{
				myApp.alert('提交成功！', '提示', function(){
					myApp.closeModal();
					location.href=location.href;				
				});

			} else if( response.result == 0) {
				myApp.alert('提交失败！', '提示');
			}
		}
	});
}); 
$$(document).on('click', '.btn-share', function(){
	var _html = '<div class="modal-overlay modal-overlay-visible"><div class="share_txt"></div></div>';
	 $$('body').append(_html);

});

$$(document).on('click', '.share_txt', function(){
	$$('.modal-overlay').hide();

});
$$(document).on('click', '.action-apply', function(){
	if(ifLogin)
	{
		myApp.openModal('.popup-apply');
		$$('.popup-apply').show();
	} else {
		var url = location.href;
		actionLogin(url);
	}
}); 

var selfBtn ;
var timerSum = 60;
function countTimer()
{
	if (timerSum>0) {
		timerSum --;
		selfBtn.html( timerSum );
		setTimeout(countTimer,1000);
	}else{
		timerSum = 60;
		selfBtn.html( selfBtn.attr('label') );
		selfBtn.removeClass('btn-disable');
	}
}
$$(document).on('click', '.sendCodeBtn', function(){
	if ( $$(this).hasClass('btn-disable') ) {
		return;
	}
	selfBtn = $$(this);
	selfBtn.addClass('btn-disable');
	var post_url = $$(this).attr('href');
	var obj = $$( $$(this).attr('field') );
	var phonenum = obj.val();
	$$.ajax({
		url:post_url,
		method:'POST',
		data: {phone:phonenum},
		success: function(res){
			if ( res.status == 200 ){
				selfBtn.attr('label', selfBtn.text());
				timerSum = 60;				
				countTimer();
			}else{
				selfBtn.removeClass('btn-disable');
			}
			alert(res.info);
		},
		dataType:'json'
	});
});
